package com.mi.proxy6;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class MyMethodInterceptor implements MethodInterceptor {

	private static Properties proxyConf;
	private static Map<String,String> confMap;
	{
		proxyConf = new Properties();
		try {
			proxyConf.load(MyMethodInterceptor.class.getResourceAsStream("proxy.properties"));
			confMap = new HashMap<String,String>();
			String proxyRulesStr = proxyConf.getProperty("proxyRules");
			if(proxyRulesStr != null){
				String[] proxyRules = proxyRulesStr.split(",");
				for (String proxyRule : proxyRules) {
					String[] rule = proxyRule.split(":");
					confMap.put(rule[0], rule[1]);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//持有的被代理对象real对象，Object
	private Object object;
	
	public MyMethodInterceptor(Object object) {
		super();
		this.object = object;
	}

	@Override
	public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
		String realObjClassName = object.getClass().getName();
		String methodName = method.getName();
		String key = realObjClassName + "-" + methodName;
		String value = confMap.get(key);
		if(value == null){
			value = confMap.get(realObjClassName + "-*");
			if(value == null){
				return method.invoke(object, args);
			}
		}
		
		
		if(value.equals("before")){
			System.out.println("毛爷爷万岁！");
			return method.invoke(object, args);
		}
		
		if(value.equals("after")){
			Object reVal = method.invoke(object, args);
			System.out.println("毛爷爷万岁！");
			return reVal;
		}
		
		return method.invoke(object, args);
	}

}
